<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>9-封装-简易axios函数-获取地区列表</title>
</head>
<body>
    <h2>封装-简易axios函数-获取地区列表</h2>
    <div class="box"></div>
    <script>
        function myAxios(config) {
            return new Promise((resolve, reject) => {
                const xhr = new XMLHttpRequest()
                // 1. 判断params属性
                if(config.params) {
                    // 2. 生成查询参数
                    const params = new URLSearchParams(config.params)
                    const query = params.toString()
                    console.log(query)
                    
                    // 3.拼接查询参数
                    config.url += `?${query}`
                    console.log(config.url)
                }
                xhr.open(config.method || 'GET',config.url)
                xhr.addEventListener('loadend',() => {
                    if(xhr.status >=200 && xhr.status < 300) {
                        resolve(JSON.parse(xhr.response))
                    } else {
                        reject(new Error(xhr.response))
                    }
                })
                xhr.send()
            })
        }

        // 4. 调用函数实现功能
        myAxios({
            url:'https://hmajax.itheima.net/api/area',
            params:{
                pname:'黑龙江省',
                cname:'哈尔滨市'
            }
            // method 'get'
        }).then(res => {
            console.log(res)
            document.querySelector('.box').innerHTML = res.list  
        })

    </script>
</body>
</html>